<template>
  <bfe-dialog
    :title="title === 'add' ? $t('stm.common.add') : $t('stm.common.edit')"
    :close-on-click-modal="false"
    :visible.sync="showFlag"
    @close="handCancel"
    width="80%"
  >
    <bfe-form
      ref="formObj"
      :rules="formRules"
      :model="formObj"
      label-position="top"
      v-loading="loading"
      class="appproval"
    >
      <bfe-form-item
        label="一级行机构编号"
        prop="orgRefno"
        style="width: calc((100% - 32px) / 3); float: left"
      >
        <bfe-select
          v-model="formObj.orgRefno"
          size="small"
          :disabled="title !== 'add'"
          @change="getOrgName"
          filterable
          :placeholder="$t('tooltip.please-select')"
        >
          <bfe-option
            v-for="item in selectObj['stm_rfi_one_org'][language]"
            :key="item.value"
            :label="item.value + '-' + item.label"
            :value="item.value"
          >
          </bfe-option>
        </bfe-select>
      </bfe-form-item>

      <bfe-form-item
        label="一级行机构名称"
        prop="orgRefno"
        style="width: calc((100% - 32px) / 3); margin-left: 16px; float: left"
      >
        <bfe-select
          v-model="formObj.orgRefno"
          size="small"
          disabled
          :placeholder="$t('tooltip.please-select')"
        >
          <bfe-option
            v-for="item in selectObj['stm_rfi_one_org'][language]"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          >
          </bfe-option>
        </bfe-select>
      </bfe-form-item>

      <bfe-form-item
        label="设置顺序层级"
        prop="orderDesc"
        style="width: calc((100% - 32px) / 3); margin-left: 16px; float: left"
      >
        <bfe-select
          v-model="formObj.orderDesc"
          size="small"
          :placeholder="$t('tooltip.please-select')"
          @change="changeOrder"
          multiple
        >
          <bfe-option
            v-for="item in orderList"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          >
          </bfe-option>
        </bfe-select>
      </bfe-form-item>

      <vxe-table :data="formObj.apprDetail" border class="tableList">
        <vxe-table-column title="审核层级">
          <template #default="{ row, rowIndex }">
            <bfe-form-item
              label
              :prop="`apprDetail.${rowIndex}.selOptions`"
              :rules="formRules.selOptions"
            >
              <bfe-cascader
                :options="options"
                size="small"
                @change="(val) => getSelOptions(val, rowIndex)"
                v-model="formObj.apprDetail[rowIndex].selOptions"
              >
              </bfe-cascader>
            </bfe-form-item>
          </template>
        </vxe-table-column>

        <vxe-table-column title="客户类型">
          <template #default="{ row, rowIndex }">
            <bfe-form-item
              label
              :prop="`apprDetail.${rowIndex}.custType`"
              :rules="formRules.custType"
            >
              <bfe-select
                v-model="formObj.apprDetail[rowIndex].custType"
                size="small"
                @change="changeCustTp(rowIndex)"
                :placeholder="$t('tooltip.please-select')"
              >
                <bfe-option
                  v-for="item in selectObj['stm_rfiCusTp'][language]"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                >
                </bfe-option>
              </bfe-select>
            </bfe-form-item>
          </template>
        </vxe-table-column>

        <vxe-table-column title="顺序">
          <template #default="{ row, rowIndex }">
            <bfe-form-item
              :prop="`apprDetail.${rowIndex}.adtOrder`"
              :rules="formRules.adtOrder"
            >
              <bfe-input
                v-model="formObj.apprDetail[rowIndex].adtOrder"
                :disabled="formObj.apprDetail[rowIndex].orderDisable"
                size="small"
                :maxlength="2"
                type="input"
                :placeholder="$t('stm.common.pleaseInput')"
              ></bfe-input>
            </bfe-form-item>
          </template>
        </vxe-table-column>

        <vxe-table-column title="审核节点数">
          <template #default="{ row, rowIndex }">
            <bfe-form-item
              :prop="`apprDetail.${rowIndex}.adtCnt`"
              :rules="formRules.adtCnt"
            >
              <bfe-input
                v-model="formObj.apprDetail[rowIndex].adtCnt"
                size="small"
                :maxlength="1"
                type="input"
                :placeholder="$t('stm.common.pleaseInput')"
              ></bfe-input>
            </bfe-form-item>
          </template>
        </vxe-table-column>

        <vxe-table-column title="审核时限(小时)">
          <template #default="{ row, rowIndex }">
            <bfe-form-item
              :prop="`apprDetail.${rowIndex}.adtTmlmtHr`"
              :rules="formRules.adtTmlmtHr"
            >
              <bfe-input
                v-model="formObj.apprDetail[rowIndex].adtTmlmtHr"
                size="small"
                :maxlength="11"
                type="input"
                :placeholder="$t('stm.common.pleaseInput')"
              ></bfe-input>
            </bfe-form-item>
          </template>
        </vxe-table-column>

        <vxe-table-column title="操作" width="120">
          <template #default="{ row, rowIndex }">
            <bfe-button
              type="text"
              @click="delList(rowIndex)"
              v-if="formObj.apprDetail && formObj.apprDetail.length !== 1"
              >删除</bfe-button
            >

            <bfe-button
              type="text"
              @click="addList"
              v-if="rowIndex === formObj.apprDetail.length - 1"
              >新增</bfe-button
            >
          </template>
        </vxe-table-column>
      </vxe-table>
    </bfe-form>

    <span slot="footer" class="dialog-footer">
      <bfe-button @click="handCancel" :loading="loading">{{
        $t("stm.common.cancel")
      }}</bfe-button>

      <bfe-button type="primary" @click="handConfirm" :loading="loading">{{
        $t("stm.common.confirm")
      }}</bfe-button>
    </span>
  </bfe-dialog>
</template>

<script>
import microService from "@/micro-service";
import apisRegister from "@/api";

export default {
  props: {
    selectObj: {
      type: Object,
      default: () => {},
    },
  },
  data() {
    return {
      showFlag: false,
      title: "",
      loading: false,
      formObj: {
        apprDetail: [],
        orderDesc: [],
      },
      formRules: {
        orgRefno: [
          {
            required: true,
            message: this.$t("tooltip.please-select"),
            trigger: "change",
          },
        ],
        selOptions: [
          {
            validator: (rule, value, callback) => {
              if (!value || !value.length) {
                callback(new Error("请选择"));
              }
              callback();
            },
            required: true,
            trigger: "blur",
          },
        ],
        custType: [
          {
            required: true,
            message: this.$t("tooltip.please-select"),
            trigger: "change",
          },
        ],
        adtCnt: [
          {
            validator: (rule, value, callback) => {
              if (!value) {
                callback(new Error("请输入"));
              }
              const reg = /^([1-9][0-9]*)$/;
              if (!reg.test(value)) {
                callback(new Error("请输入非0正整数"));
              }
              callback();
            },
            required: true,
            trigger: "blur",
          },
        ],
        adtTmlmtHr: [
          {
            validator: (rule, value, callback) => {
              if (!value) {
                callback(new Error("请输入"));
              } // const reg = /^[0-9]+(.[0-9]{2})?$/
              const reg = /^([1-9][0-9]*)$/;
              if (!reg.test(value)) {
                callback(new Error("请输入非0正整数"));
              }
              callback();
            },
            required: true,
            trigger: "blur",
          },
        ],
        adtOrder: [
          {
            validator: (rule, value, callback) => {
              if (!value) {
                callback();
              }
              const reg = /^([1-9][0-9]*)$/;
              if (!reg.test(value)) {
                callback(new Error("请输入非0正整数"));
              }
              callback();
            },
            required: false,
            trigger: "blur",
          },
        ],
      },
      options: [],
      apprDep: {},
      orderList: [],
    };
  },
  computed: {
    language() {
      return this.$store.state.base.language;
    },
  },
  methods: {
    initData(type, data = {}) {
      this.title = type;
      if (type === "add") {
        this.formObj = {
          apprDetail: [{ orderDisable: true }],
          orderDesc: [],
        };
      } else {
        this.getPageData(data);
      }
      console.log(this.selectObj, "=====");
      const rfiApprLevel = this.selectObj.stm_rfiApprLevel[this.language];
      const rfiCusTp = this.selectObj.stm_rfiCusTp[this.language];
      let formArr = {
        arr1: this.selectObj.stm_rfiApprRoleOne[this.language],
        arr2: this.selectObj.stm_rfiApprRoleTwo[this.language],
        arr3: this.selectObj.stm_rfiApprRoleThree[this.language],
      };
      this.options = rfiApprLevel.map((item, index) => {
        return {
          value: item.value,
          label: item.label,
          children: formArr["arr" + (index + 1)],
        };
      });
      this.orderList = [];
      rfiApprLevel.map((item) => {
        rfiCusTp.map((val) => {
          this.orderList.push({
            value: val.value + "_" + item.value,
            label: val.label + "_" + item.label,
          });
        });
      });
      console.log(this.orderList, "orderList");
      this.showFlag = true;
    },
    changeOrder() {
      if (!this.formObj.apprDetail) {
        return;
      }
      this.formObj.apprDetail.map((item, index) => {
        const { apprLevel, custType } = item;
        const str = custType + "_" + apprLevel;
        if (this.formObj.orderDesc.includes(str)) {
          this.$set(this.formObj.apprDetail[index], "orderDisable", false);
        } else {
          this.$set(this.formObj.apprDetail[index], "orderDisable", true);
          this.$set(this.formObj.apprDetail[index], "adtOrder", "");
        }
      });
    },
    changeCustTp(index) {
      const { apprLevel, custType } = this.formObj.apprDetail[index];
      const str = custType + "_" + apprLevel;
      if (this.formObj.orderDesc.includes(str)) {
        this.$set(this.formObj.apprDetail[index], "orderDisable", false);
      } else {
        this.$set(this.formObj.apprDetail[index], "orderDisable", true);
        this.$set(this.formObj.apprDetail[index], "adtOrder", "");
      }
    },
    getSelOptions(val, index) {
      if (!val || !val.length) return;
      this.$set(this.formObj.apprDetail[index], "apprLevel", val[0]);
      this.$set(this.formObj.apprDetail[index], "apprRole", val[1]);
      const { apprLevel, custType } = this.formObj.apprDetail[index];
      const str = custType + "_" + apprLevel;
      if (this.formObj.orderDesc.includes(str)) {
        this.$set(this.formObj.apprDetail[index], "orderDisable", false);
      } else {
        this.$set(this.formObj.apprDetail[index], "orderDisable", true);
        this.$set(this.formObj.apprDetail[index], "adtOrder", "");
      }
    },
    getOrgName(val) {
      console.log(val, "======val");
      if (!val || !val.length) {
        this.formObj = {
          ...this.formObj,
          orgName: "",
        };
        return;
      }
      const arr = this.selectObj["stm_rfi_one_org"][this.language];
      const orgArr = _.filter(arr, (item) => item.value === val) || [];
      console.log(orgArr, "orgArr====");
      if (!orgArr || !orgArr.length) {
        this.formObj = {
          ...this.formObj,
          orgName: "",
        };
        return;
      }
      this.formObj = {
        ...this.formObj,
        orgName: orgArr[0].label,
      };
    },
    handCancel() {
      this.showFlag = false;
      this.formObj = {
        orderDesc: [],
      };
      this.changeFlag = false;
      this.$refs.formObj.resetFields();
    },
    delList(index) {
      this.formObj.apprDetail.splice(index, 1);
    },
    addList() {
      let selOptionsFlag = false;
      let custTypeFlag = false;
      let adtCntFlag = false;
      let adtTmlmtHrFlag = false;

      const len = this.formObj.apprDetail.length;
      this.$refs.formObj.validateField(
        `apprDetail.${len - 1}.selOptions`,
        (errMsg) => {
          if (!errMsg) {
            console.log(errMsg, "errMsg===");
            selOptionsFlag = true;
          }
        }
      );
      this.$refs.formObj.validateField(
        `apprDetail.${len - 1}.custType`,
        (errMsg) => {
          if (!errMsg) {
            console.log(errMsg, "errMsg===");
            custTypeFlag = true;
          }
        }
      );
      this.$refs.formObj.validateField(
        `apprDetail.${len - 1}.adtCnt`,
        (errMsg) => {
          if (!errMsg) {
            console.log(errMsg, "errMsg===");
            adtCntFlag = true;
          }
        }
      );
      this.$refs.formObj.validateField(
        `apprDetail.${len - 1}.adtTmlmtHr`,
        (errMsg) => {
          if (!errMsg) {
            console.log(errMsg, "errMsg===");
            adtTmlmtHrFlag = true;
          }
        }
      );
      selOptionsFlag &&
        custTypeFlag &&
        adtCntFlag &&
        adtTmlmtHrFlag &&
        this.formObj.apprDetail.push({ orderDisable: true });
    },
    handConfirm() {
      this.$refs.formObj.validate((ok) => {
        if (ok) {
          this.loading = true;
          const params = {
            payload: {
              ...this.formObj,
              crtDttm: null,
              modDttm: null,
            },
          };
          const api =
            this.title === "add" ? "_01_TSTM04ADD893" : "_01_TSTM04MOD890";
          microService(apisRegister[api], "", params)
            .then((res) => {
              if (res.optMsgInfo && res.optMsgInfo.optStatus === "success") {
                this.handCancel();
                this.$emit("doSearch");
              }
            })
            .finally(() => {
              this.loading = false;
            });
        }
      });
    },
    getPageData(data) {
      const params = {
        payload: {
          orgRefno: data.orgRefno,
          optTp: "queryOne",
        },
      };
      this.$p2svr(this.$api["_01_TSTM04GET892"], "", params)
        .then((res) => {
          if (res.payload) {
            this.formObj = {
              ...res.payload,
              orderDesc: res.payload.orderDesc || [],
            };
            this.formObj.apprDetail = this.formObj.apprDetail.map((item) => {
              const { apprLevel, custType } = item;
              const str = custType + "_" + apprLevel;
              return {
                ...item,
                selOptions: [item.apprLevel, item.apprRole],
                orderDisable: this.formObj.orderDesc.includes(str),
              };
            });
          }
        })
        .finally(() => {
          this.loading = false;
        });
    },
  },
};
</script>

<style lang="less" scoped>
@import "../../../style/stm.less";
.appproval /deep/.giop-form-item {
  width: 100%;
  float: left;
}

.tableList {
  margin-bottom: 16px;
  width: 100%;
  float: left;
  overflow: hidden;
  /deep/.giop-form-item {
    margin-bottom: 0;
  }
  /deep/.cell {
    padding: 6px 10px;
  }
  /deep/.giop-form-item__error {
    position: relative;
    padding: 0 0 4px;
  }
  /deep/.giop-input--small .giop-input__inner {
    height: 30px !important;
  }
  /deep/.giop-form-item {
    margin-bottom: 0;
  }
  /deep/.giop-cascader {
    width: 100%;
  }
  /deep/.giop-cascader--small .giop-cascader__label {
    line-height: 36px;
  }
}
</style>